package com.bigdatastudio.auth.utils;

import com.bigdatastudio.auth.entity.UserDetailsModel;
import com.bigdatastudio.common.entity.User;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.JwtBuilder;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author xiao_jie
 * @date 2022-09-24 15:01
 * @describe 生成token的工具类
 */
@Data
@AllArgsConstructor
@NoArgsConstructor
@Configuration
public class TokenUtil {
    //盐
    String key = "bigdatastudio";
    //过期时间  -- 一天
    private long ttl = 3600000 * 24;

    private Map<String, String> tokenMap = new ConcurrentHashMap<>(32);

    /**
     * 生成JWT
     *
     * @param id      用户id
     * @param subject 用户信息
     * @return
     */
    public String createJWT(String id, String subject) {
        //signWith(SignatureAlgorithm.HS256, key) 设置加密方式，和盐 。盐自己规定
        long nowMillis = System.currentTimeMillis();
        Date now = new Date(nowMillis);
        JwtBuilder builder = Jwts.builder().setId(id)
                .setSubject(subject)
                .setIssuedAt(now)
                .signWith(SignatureAlgorithm.HS256, key);
        if (ttl > 0) {
            //设置过期时间
            builder.setExpiration(new Date(nowMillis + ttl));
        }
        return builder.compact();
    }

    /**
     * 解析JWT
     *
     * @param token
     * @return
     */
    public Claims parseJWT(String token) {
        return Jwts.parser()
                .setSigningKey(key)
                .parseClaimsJws(token)
                .getBody();
    }


    // 判断token是否过期
    public boolean isTokenExpired(String token) {
        Claims claims = parseJWT(token);
        Date expiration = claims.getExpiration();
        return new Date().before(expiration);
//        return expiration.before(new Date());
    }

    // 存储token，便于以后拿出来对比是否过期
    public void putToken(String uuid, String token) {
        tokenMap.put(uuid, token);
    }

    // 判断token是否是最新生成的
    public boolean isNewToken(String uuid, String token) {
        if (uuid != null && tokenMap.containsKey(uuid) && tokenMap.get(uuid).equals(token)) {
            return true;
        }
        return false;
    }

    // 删除存储的token
    public void deleteToken(String uuid) {
        tokenMap.remove(uuid);
    }

    // 从token中获取用户信息
    public static User getJwtUser() {
        User user = null;
        try {
            Object obj = SecurityContextHolder.getContext().getAuthentication().getPrincipal();
            UserDetailsModel userDetailsModel = (UserDetailsModel) obj;
            user = userDetailsModel.getUser();
        } catch (Exception ex) {
            throw new RuntimeException();
        }
        return user;
    }

}
